package com.xiaobaibai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaobaibai.common.IndexEnum;
import com.xiaobaibai.dao.IndexProductDao;
import com.xiaobaibai.entity.IndexProduct;
import com.xiaobaibai.entity.Product;
import com.xiaobaibai.response.ResponseFormat;
import com.xiaobaibai.service.IIndexProductService;
import com.xiaobaibai.service.IProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaobaibai
 * @since 2020-10-16
 */
@Service
public class IndexProductServiceImpl extends ServiceImpl<IndexProductDao, IndexProduct> implements IIndexProductService {

    @Autowired
    IProductService productService;

    @Override
    public void deleteNewByIds(List<Integer> list, Integer type) {
        this.baseMapper.deleteNewByIds(list,type);
    }

    @Override
    public ResponseFormat addIndexProduct(List<Integer> list,IndexEnum indexEnum){
        QueryWrapper<Product> queryWrapper=new QueryWrapper<>();
        queryWrapper.in("id",list);
        queryWrapper.select("id","product_name","product_image","product_unit","product_old_price","product_price");
        List<Product> productList = productService.list(queryWrapper);
        QueryWrapper<IndexProduct> q=new QueryWrapper<>();
        q.select("product_id");
        q.eq("type",indexEnum.getCode());
        List<IndexProduct> alreadyList=this.list(q);
        Set<Integer> set=alreadyList.stream().map(IndexProduct::getProductId).collect(Collectors.toSet());

        List<IndexProduct> indexProductList=new ArrayList<>();
        productList.forEach(p->{
            if(!set.contains(p.getId())){
                IndexProduct indexProduct=new IndexProduct();
                BeanUtils.copyProperties(p,indexProduct);
                indexProduct.setId(null);
                indexProduct.setProductId(p.getId());
                indexProduct.setType(indexEnum.getCode());
                indexProduct.setProductImage(p.getProductImage().get(0));
                indexProductList.add(indexProduct);
            }
        });

        if(indexProductList.size()==0) {
            if(indexEnum== IndexEnum.REXIAO)
                return ResponseFormat.ok("已经都是热销推荐了");
            else
                return ResponseFormat.ok("已经都是新品推荐了");
        }

        this.saveBatch(indexProductList);

        if(indexEnum==IndexEnum.REXIAO)
            return ResponseFormat.ok("热销推荐成功");
        else
            return ResponseFormat.ok("新品推荐成功");
    }

}
